
var height = window.screen.height - 120;
var urlParams = new URLSearchParams(window.location.search);
var query = Object.fromEntries(urlParams.entries());
var _name = 'h';
if (query[_name]) {
    height = query[_name];
}
var mdEditor = window.mdEditor;
var isChanged = false;
var saveFileFn = null;
var task = 0;

if(document.location.hostname)
{
    if (document.location.hostname.indexOf('.') < 0) {
        document.domain = document.location.hostname;
    }
    else {
        document.domain = document.location.hostname.substring(document.location.hostname.indexOf('.') + 1);
    }

}
 
/**
 * @description 绑定预览 事件
 * @param {*} callback 
 */
window.bindPreviewEvent = function (callback) {
    if (mdEditor) {
        mdEditor.on('previewed', function () {
            if (callback) {
                callback(mdEditor.state.preview);
            }
        });

        mdEditor.on('previewing', function () {
            if (callback) {
                callback(mdEditor.state.preview);
            }
        });
    }
}
/**
 * @description 设置保存文件的方法
 * @param {*} saveFn 
 */
window.bindSaveFunction = function (saveFn) {
    saveFileFn = saveFn;
}
/**
 * @description 预览文件
 */
window.previewFile = function () {
    mdEditor && mdEditor.previewing();
}
/**
 * @description 获取 Markdown 源码
 * @returns 
 */
window.getMdCode = function () {
      // 获取 Markdown 源码 
        // 获取 Textarea 保存的 HTML 源码
    return  mdEditor && mdEditor.getMarkdown();//alert(code);  
}
 
/**
 * @description 获取html
 */
window.getHTML = function () {
 
    return mdEditor && mdEditor.getHTML();
}

window.run = function run() {
 
 if (!window.render) { 
        console.error("window.render is not found");
        return;
    }
    //对接其他异步渲染引擎
    mdEditor.onRender = function(id,lang,diagramType,code)
    {
         //console.debug('替换输出中的占位符('+id+')',lang,diagramType,code);
         window.frames[0].document.getElementById(id).innerHTML = code;
    }
    //
    document.getElementById('markdown').onkeydown = function (evt) {
        
        isChanged = true;

        if (evt.ctrlKey) {
            if (evt.key == 's' || evt.key == 'S') {
                if (saveFileFn) {
                    saveFileFn();
                }
                evt.returnValue = false;
            }
        }
    };

    fetch(top.Rsd.getRedjsUrl('plugin/marked/app/initial.md'))
      .then(res => res.text())
      .then(text => {
         window.render(text)
      });
 
};
 
function setInitialQuickref() {
  return fetch(top.Rsd.getRedjsUrl('plugin/marked/app/quickref.md'))
    .then(res => res.text())
    .then(text => {
      document.querySelector('#outer').value = text;
    });
}